#include "GY_InsertWidgetControl.h"
#include "ui_GY_InsertWidgetControl.h"



GY_InsertWidgetControl::GY_InsertWidgetControl(QWidget *parent):
    QWidget(parent),
    ui(new Ui::GY_InsertWidgetControl)
{
    ui->setupUi(this);
    setupLayout();
}

GY_InsertWidgetControl::~GY_InsertWidgetControl()
{
    clear();
    if(m_layout)
    {
        delete  m_layout;
        m_layout = nullptr;
    }
}

QHBoxLayout *GY_InsertWidgetControl::createRowLayout()
{
    QHBoxLayout *rowLayout = new QHBoxLayout();
    rowLayout->setSpacing(m_colSpacing);
    return rowLayout;
}

void GY_InsertWidgetControl::setupLayout()
{
    //设置界面
    ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_layout = new QVBoxLayout(ui->scrollAreaWidgetContents);
    ui->scrollAreaWidgetContents->setLayout(m_layout);

   QSpacerItem *spacer = new QSpacerItem(QSizePolicy::Minimum, QSizePolicy::Expanding);
   m_layout->addItem(spacer);
    //初始化列数
    m_colCount = this->width() / m_insertWidgetWidth;

}


void GY_InsertWidgetControl::setWidgetSize(const int &height, const int &widgth)
{
    if(m_allSaveWidgetList.size() > 0)
    {
        m_insertWidgetHeight = height;
        m_insertWidgetWidth = widgth;
        //计算获取当前界面大小 拿到最新列数更新布局
        int currWidgetWidgth = this->width();
        int col = currWidgetWidgth / m_insertWidgetWidth;

        //更新布局
        m_colCount = col;
        updateCurrLayout();

        if(m_colCount >= m_allSaveWidgetList.size())
        {
            //删除首行的空白界面
            QHBoxLayout *currRwoLayout = dynamic_cast<QHBoxLayout*>(m_layout->itemAt(m_layout->count() - 1));
            if(currRwoLayout && getCurrRowInsertNullControl(currRwoLayout))
            {
                clearEmptyControl(currRwoLayout);
            }
        }
    }
}

void GY_InsertWidgetControl::updateCurrLayout()
{
    QLayoutItem *item;
    while((item = m_layout->takeAt(0)) != nullptr)
    {
        delete  item;
        item = nullptr;
    }
    for(int i = 0; i < m_allSaveWidgetList.size(); i++)
    {
        addWidget(m_allSaveWidgetList.at(i));
    }
}

bool GY_InsertWidgetControl::removeWidget(QWidget *widget)
{
    if(widget && m_allSaveWidgetList.contains(widget))
    {
        m_allSaveWidgetList.removeOne(widget);
        updateCurrLayout();
        if(m_currSelectWidget == widget)
            m_currSelectWidget = nullptr;
        delete  widget;
        widget = nullptr;
        return true;
    }
    return false;
}

void GY_InsertWidgetControl::clear()
{
    QLayoutItem *item;
    while((item = m_layout->takeAt(0)) != nullptr)
    {
        delete  item;
    }

    QList<QWidget*>::iterator itor = m_allSaveWidgetList.begin();
    while(itor != m_allSaveWidgetList.end())
    {
        if(m_allSaveWidgetList.removeOne(*itor))
        {
            if((*itor))
            {
                delete  (*itor);
                (*itor) = nullptr;
            }
            itor++;
        }
    }
    m_allSaveWidgetList.clear();
}

QWidget *GY_InsertWidgetControl::getCurrSelectWidget()
{
    if(m_currSelectWidget)
        return m_currSelectWidget;
    return nullptr;
}

QWidget *GY_InsertWidgetControl::getWidget(const int &findRow, const int &findCol)
{
    QWidget * widget = nullptr;

    if(findRow < 0 && findCol < 0)
    {
        return widget;
    }

    int insertRow = findRow;
    int insetCol = findCol;

    //目标位置之前的行数 *当前列 计算目标位置前一行的总数据
    int index = (insertRow - 1) * m_colCount;

    //如果目标位置小于0，则是第一行
    if(index <= 0)
        index = 0;

    //获取目标位置
    index += insetCol - 1;
    if(index >= 0 && index <= m_allSaveWidgetList.size() && index <= m_layout->count())
    {
        if(m_allSaveWidgetList.at(index))
            return m_allSaveWidgetList.at(index);
    }
    return widget;
}

InesertWidgetIndex GY_InsertWidgetControl::getWidgetIndex(const QWidget *targetWidget)
{
    InesertWidgetIndex index;

    //如果目标widget为空 则返回当前点击的widget下标
    if(targetWidget == nullptr && m_currSelectWidget)
    {
        targetWidget = m_currSelectWidget;
    }
    for(int row = m_layout->count() - 1; row >= 0; row--)
    {
        QHBoxLayout *everyRowLayout = dynamic_cast<QHBoxLayout*>(m_layout->itemAt(row));
        for(int col = everyRowLayout->count() - 1; col >= 0; col--)
        {
            QWidget *findWidget = dynamic_cast<QWidget *>(everyRowLayout->itemAt(col)->widget());
            if(findWidget == targetWidget)
            {
                index.row = row + 1;
                index.col = col + 1;
                return index;
            }
        }
    }
    return index;
}

int GY_InsertWidgetControl::getCurrRowInsertNullControl(QHBoxLayout *layout)
{
    int count = 0;
    for(int i = 0; i < layout->count(); i++)
    {
        if(!dynamic_cast<PaddingTransparentWidget *>(layout->itemAt(i)->widget()))
        {
            count++;
        }
    }
    return count;
}

void GY_InsertWidgetControl::clearEmptyControl(QHBoxLayout *layout)
{
    if(layout)
    {
        for(int i = layout->count() - 1; i >= 0; i--)
        {
            PaddingTransparentWidget *transparentWidget = dynamic_cast<PaddingTransparentWidget *>(layout->itemAt(i)->widget());
            if(transparentWidget)
                delete layout->takeAt(i);
        }
    }
}

void GY_InsertWidgetControl::setRowSpacing(const int &spacing)
{
    if(spacing >=0)
    {
        m_layout->setSpacing(spacing);
        updateCurrLayout();
    }
}

void GY_InsertWidgetControl::setColSpacing(const int &spacing)
{
    if(spacing >= 0)
    {
        m_colSpacing = spacing;
        updateCurrLayout();
    }
}

bool GY_InsertWidgetControl::inertWidget(const int &row, const int &col, QWidget *insertWidget)
{
    if(insertOrRemoveOn(row, col,0, insertWidget))
        return true;
    return false;
}

bool GY_InsertWidgetControl::removeOneWidget(const int &row, const int &col)
{
    if(m_allSaveWidgetList.isEmpty())
        return false;
    if(insertOrRemoveOn(row, col,1))
        return true;
    return false;
}


QList<QWidget *> GY_InsertWidgetControl::getAllWidget()
{
    return m_allSaveWidgetList;
}

void GY_InsertWidgetControl::resetWidget()
{
    updateCurrLayout();
}

bool GY_InsertWidgetControl::insertOrRemoveOn(const int &row, const int &col, const int &flag, QWidget *targetWidget)
{
    if(targetWidget == nullptr && flag == 0)
        return  false;

    if(row < 0 && col < 0)
        return false;

    int insertRow = row;
    int insetCol = col;

    //目标位置之前的行数 *当前列 计算目标位置前一行的总数据
    int index = (insertRow - 1) * m_colCount;

    //如果目标位置小于0，则是第一行
    if(index < 0)
        index = 0;

    //获取目标位置
    index += insetCol - 1;
    if(index >= 0)
    {
        if(flag == 0)
        {
            if(col > m_colCount)
                return  false;
            //添加
            if(!m_allSaveWidgetList.contains(targetWidget))
            {
                m_allSaveWidgetList.insert(index, targetWidget);
                updateCurrLayout();
                return true;
            }
        }
        else
        {
            //删除
            QWidget *widget = getWidget(row,col);
            if(widget && m_allSaveWidgetList.contains(widget))
            {
                m_allSaveWidgetList.removeOne(widget);
                if(widget)
                {
                    delete  widget;
                    widget = nullptr;
                }
                updateCurrLayout();
                if(m_currSelectWidget == targetWidget)
                {
                    m_currSelectWidget = nullptr;
                }
                return true;
            }



        }
    }
    return false;
}

void GY_InsertWidgetControl::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);

    //计算获取当前界面大小 拿到最新列数更新布局
    int currWidgetWidgth = this->width();

    int col = currWidgetWidgth / m_insertWidgetWidth;

    //再次布局
    if(col != m_colCount && col > 0 )
    {

        m_colCount = col;
        updateCurrLayout();
    }
}

void GY_InsertWidgetControl::mousePressEvent(QMouseEvent *event)
{
    switch((int)event->button())
    {
    case Qt::MouseButton::LeftButton:
    {
        for(int i = 0; i < m_allSaveWidgetList.size(); i++)
        {
            if(m_allSaveWidgetList.at(i))
            {
                QRect widgetRect = m_allSaveWidgetList.at(i)->geometry();
                if(widgetRect.contains(event->pos()))
                {
                    m_currSelectWidget = m_allSaveWidgetList.at(i);
                    emit sigWidgetClicked(getWidgetIndex(m_allSaveWidgetList.at(i)),m_allSaveWidgetList.at(i));
                    break;
                }
            }
        }
    }break;
    }
}

void GY_InsertWidgetControl::mouseDoubleClickEvent(QMouseEvent *event)
{
    switch((int)event->button())
    {
    case Qt::MouseButton::LeftButton:
    {
        for(int i = 0; i < m_allSaveWidgetList.size(); i++)
        {
            if(m_allSaveWidgetList.at(i))
            {
                QRect widgetRect = m_allSaveWidgetList.at(i)->geometry();
                if(widgetRect.contains(event->pos()))
                {
                    m_currSelectWidget = m_allSaveWidgetList.at(i);
                    emit sigWidgetDoubleClicked(getWidgetIndex(m_allSaveWidgetList.at(i)),m_allSaveWidgetList.at(i));
                    break;
                }
            }
        }
    }break;
    }
}

